package com.service.atm;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.bpms.InitServlet;
import com.bpms.common.CommonUtil;
import com.bpms.common.Param;
import com.bpms.common.VO;
import com.bpms.eai.IPackage;
import com.bpms.eai.ISyncComm;
import com.bpms.esb.IService;
import com.service.uai.engine.comm.HDPrintClient;
import com.service.uai.engine.pack.HDPrintClientPack;

public class Sendhdprintmsg implements IService {

	public VO exec(VO arg0) {
		String test = Param.getValue("UAI", "atm_send_demo");

		try {
			if ("Y".equals(test)) {
				SAXBuilder builder = new SAXBuilder();
				String testPath = InitServlet.RealPath + "/xml/testprint.xml";
				Document document = builder.build(new File(testPath));
				return parseXml(document);
			} else {
				IPackage pack=new HDPrintClientPack();
				ISyncComm syncComm=new HDPrintClient();
				byte[] buffer=pack.prepareBuffer("print", arg0);
				if(buffer==null) return null;
				byte[] resultBuffer=syncComm.sendBuffer(buffer);
				if(resultBuffer==null) return null;
				VO resultVO=pack.parseBuffer(resultBuffer);
				return resultVO;
			}
		} catch (Exception e) {
			CommonUtil.debug("Sendhdprintmsg op file error", e);
		}

		return null;
	}

	public VO parseXml(Document document) {
		VO vo = new VO();
		Element root = document.getRootElement();
		Element edecl = (Element) root.getChildren("gDecl").get(0);
		Element cMsgType = (Element) edecl.getChildren().get(0);
		vo.setAttr(cMsgType.getName(), cMsgType.getValue());
		List body = ((Element) (root.getChildren("gTxData").get(0)))
				.getChildren();
		for (Iterator it = body.iterator(); it.hasNext();) {
			Element el = (Element) it.next();
			vo.setAttr(el.getName(), el.getValue());
		}
		return vo;
	}
}
